package com.hcinfos.gsoo.ui;

import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Constants;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.db.NewDBUtil;
import com.hcinfos.gsoo.enity.OrderMsgEnity;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.interaze.DialogCallBack;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/*
 * tab 
 */
public class ProfileActivity extends Activity implements OnClickListener {

	private Button logout_bt;
	private SharePreferenceUtil spfUtil;
	private User user = null;
	private TextView credit_tv;
	private TextView userName_tv;

	public final int LOGOUT_SUCCESS = 0x1120;
	public final int LOGOUT_FAIL = LOGOUT_SUCCESS + 1;
	public final int LOGIN_FAIL = LOGOUT_SUCCESS + 2;
	public final int LOGIN_SUCCESS = LOGOUT_SUCCESS + 3;

	private NewDBUtil newDBUtil;

	private ImageView im_setting;

	private RelativeLayout address_rl;
	private RelativeLayout diancai_rl;
	private RelativeLayout waimai_rl;
	private RelativeLayout gift_rl;
	private RelativeLayout order_rl;
	private RelativeLayout contact_us_rl;

	private TextView waimai_num_tv;
	private Dialog dialog;

	private TextView right_tv;
	private RelativeLayout my_detail_rl;

	private ObjectMapper mapper;
	public static String UPDATE_ACTION = "com.login.update.action";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		setContentView(R.layout.activity_profile);

		mapper = new ObjectMapper();
		dialog = DialogUtil.createProgressDialog(this, "提示", "正在注销中...");
		spfUtil = new SharePreferenceUtil(this, "setting");
		newDBUtil = NewDBUtil.newInstance(this);

		initRes();
	}

	private void initRes() {
		waimai_num_tv = (TextView) findViewById(R.id.waimai_num_tv);
		logout_bt = (Button) findViewById(R.id.logout_bt);
		logout_bt.setOnClickListener(this);
		credit_tv = (TextView) findViewById(R.id.credit_tv);
		userName_tv = (TextView) findViewById(R.id.userName_tv);
		im_setting = (ImageView) findViewById(R.id.im_setting);
		im_setting.setOnClickListener(this);
		address_rl = (RelativeLayout) findViewById(R.id.address_rl);
		address_rl.setOnClickListener(this);
		diancai_rl = (RelativeLayout) findViewById(R.id.diancai_rl);
		diancai_rl.setOnClickListener(this);
		waimai_rl = (RelativeLayout) findViewById(R.id.waimai_rl);
		waimai_rl.setOnClickListener(this);
		gift_rl = (RelativeLayout) findViewById(R.id.gift_rl);
		gift_rl.setOnClickListener(this);
		order_rl = (RelativeLayout) findViewById(R.id.order_rl);
		order_rl.setOnClickListener(this);

		my_detail_rl = (RelativeLayout) findViewById(R.id.my_detail_rl);
		my_detail_rl.setOnClickListener(this);
		contact_us_rl = (RelativeLayout) findViewById(R.id.contact_us_rl);
		contact_us_rl.setOnClickListener(this);

		right_tv = (TextView) findViewById(R.id.right_tv);
		right_tv.setOnClickListener(this);

		IntentFilter filter = new IntentFilter("com.login.update.action");
		registerReceiver(receiver, filter);
	}

	@Override
	public void onResume() {

		updateView();
		doLogin();

		try {
			// 外卖
			List<OrderMsgEnity> list = newDBUtil.db.findAll(Selector.from(
					OrderMsgEnity.class).where(
					WhereBuilder.b("type", "=", "0").and("isRead", "=", "0")));
			if (list != null && list.size() > 0) {
				waimai_num_tv.setText(list.size() + "");
			}
		} catch (Exception e) {

		}

		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	private String password;

	private void doLogin() {
		user = (User) spfUtil.loadObject("user");

		if (user != null) {

			password = user.getPassword();
			HttpUtils http = UtilHttp.getHttpUtils(this);
			RequestParams params = new RequestParams();
			params.addBodyParameter("user.email", user.getEmail());
			params.addBodyParameter("user.password", user.getPassword());
			http.send(HttpRequest.HttpMethod.POST, Urls.NEW_USER_LOGIN, params,
					new RequestCallBack<String>() {

						@Override
						public void onFailure(HttpException arg0, String arg1) {
						}

						@Override
						public void onSuccess(ResponseInfo<String> arg0) {
							String result = arg0.result;
							LogUtil.d("wxf", "result:" + result);
							if (result == null) {
								Message msg = handler.obtainMessage();
								msg.what = LOGIN_FAIL;
								handler.sendMessage(msg);
							} else {
								try {
									JSONObject obj = new JSONObject(result);
									String message = obj.getString("message");
									int state = obj.getInt("state");
									if (state == 200) {
										User user = mapper.readValue(
												obj.getString("data"),
												new TypeReference<User>() {
												});
										LogUtil.d("wxf", obj.getString("data")
												+ "password=" + password);
										if (user != null) {
											user.setPassword(password);
											spfUtil.saveObject(user, "user");
											spfUtil.saveSharedPreferences(
													"userName",
													user.getUsername());
										}
										handler.sendEmptyMessage(LOGIN_SUCCESS);

									} else {
										Message msg = handler.obtainMessage();
										msg.obj = message;
										msg.what = LOGIN_FAIL;
										handler.sendMessage(msg);
									}
								} catch (Exception e) {
									LogUtil.e("wxf", e.toString());
									Message msg = handler.obtainMessage();
									msg.what = LOGIN_FAIL;
									handler.sendMessage(msg);
								}
							}
						}

					});

		}

	}

	private void updateView() {

		user = (User) spfUtil.loadObject("user");
		if (user != null) {
			credit_tv.setText("积分(" + user.getGold() + ")");
			userName_tv.setText(user.getUsername() == null ? user.getGgnumber()
					: user.getUsername());
			logout_bt.setText("注销");
			right_tv.setVisibility(View.VISIBLE);
		} else {
			userName_tv.setText("未登陆,请登陆");
			logout_bt.setText("登陆");
			credit_tv.setText("积分(0)");
			im_setting.setVisibility(View.GONE);
			right_tv.setVisibility(View.GONE);
		}
	}

	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.logout_bt:
			if (user != null) {
				DialogUtil.createCallLoginDialog(ProfileActivity.this,
						"你确定要注销账户", new DialogCallBack() {

							@Override
							public void viewClick() {

							}

							@Override
							public void ok() {
								logOut();
							}

							@Override
							public void init(Object obj) {

							}

							@Override
							public void cancel() {

							}
						}, "确定", "取消");
			} else {

				intent = new Intent(this, LoginActivity.class);
				startActivity(intent);
			}
			break;

		case R.id.address_rl:
			if (user == null) {
				Toast.makeText(this, "请登陆,再操作!", 500).show();
				return;
			}
			intent = new Intent(this, OrderAdressActivity.class);
			startActivity(intent);
			break;
		case R.id.order_rl:
			if (user == null) {
				Toast.makeText(this, "请登陆,再操作!", 500).show();
				return;
			}
			intent = new Intent(this, MyOrderActivity.class);
			startActivity(intent);
			break;
		case R.id.diancai_rl:
			if (user == null) {
				Toast.makeText(this, "请登陆,再操作!", 500).show();
				return;
			}
			intent = new Intent(this, MyDiancaiActivity.class);
			startActivity(intent);
			break;
		case R.id.gift_rl:
			if (user == null) {
				Toast.makeText(this, "请登陆,再操作!", 500).show();
				return;
			}
			intent = new Intent(this, MyPayActivity.class);
			startActivity(intent);
			break;
		case R.id.waimai_rl:
			if (user == null) {
				Toast.makeText(this, "请登陆,再操作!", 500).show();
				return;
			}
			intent = new Intent(this, MyWaimaiActivity.class);
			startActivity(intent);
			try {
				newDBUtil.db.delete(OrderMsgEnity.class,
						WhereBuilder.b("type", "=", "0"));
			} catch (Exception e) {

			}
			break;
		case R.id.contact_us_rl:
			intent = new Intent(this, ContactUsActivity.class);
			startActivity(intent);
			break;
		case R.id.my_detail_rl:
			if (user == null) {
				Toast.makeText(this, "请登陆,再操作!", 500).show();
				return;
			}
			intent = new Intent(this, MyDetailActivity.class);
			startActivity(intent);
			break;
		case R.id.right_tv:
			intent = new Intent(this, UpdatePwdActivity.class);
			startActivity(intent);
			break;
		}
	}

	/**
	 * 注销
	 */
	private void logOut() {

		dialog.show();
		new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							ProfileActivity.this, Urls.USER_LOGOUT);
					if (result == null) {
						Message msg = handler.obtainMessage();
						msg.what = LOGOUT_FAIL;
						handler.sendMessage(msg);
					} else {

						JSONObject obj = new JSONObject(result);
						int state = obj.getInt("state");
						String message = obj.getString("message");
						if (state == 200) {
							Message msg = handler.obtainMessage();
							msg.what = LOGOUT_SUCCESS;
							handler.sendMessage(msg);
						} else {
							Message msg = handler.obtainMessage();
							msg.what = LOGOUT_FAIL;
							msg.obj = message;
							handler.sendMessage(msg);
						}
					}
					LogUtil.d("wxf", "result:" + result);
				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = LOGOUT_FAIL;
					handler.sendMessage(msg);
					LogUtil.d("wxf", "e:" + e.toString());
				}
			}
		}).start();
	}

	Handler handler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case LOGOUT_SUCCESS:
				sendBroadcast(new Intent("com.login.update.action"));
				dialog.dismiss();
				GsooApplication.getInstance().logout();
				user = null;
				spfUtil.removeKey("user");
				spfUtil.removeKey("userName");
				spfUtil.removeKey("password");
				spfUtil.removeKey("email");
				updateView();
				Toast.makeText(ProfileActivity.this, "注销成功", 500).show();
				right_tv.setVisibility(View.GONE);
				break;
			case LOGOUT_FAIL:
				dialog.dismiss();
				if (msg.obj != null) {
					Toast.makeText(ProfileActivity.this, msg.obj.toString(),
							500).show();
				}
				break;
			case LOGIN_FAIL:

				break;
			case LOGIN_SUCCESS:
				updateView();
				break;
			}
		};
	};

	long waitTime = 2000;
	long touchTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& KeyEvent.KEYCODE_BACK == keyCode) {
			long currentTime = System.currentTimeMillis();
			if ((currentTime - touchTime) >= waitTime) {
				Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
				touchTime = currentTime;
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// Toast.makeText(ProfileActivity.this, "登录广播", 500).show();
			updateView();
		}

	};

}
